<template>
    <div>
      <!-- 表单区域 -->
      <el-form :model="form" label-width="90px" class="form-area">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据编号" >
              <el-input v-model="form.documentCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务类型">
              <el-select v-model="form.businessType" placeholder="请选择" disabled>
                <el-option label="委外退料" value="委外退料" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="跟单编号">
              <el-input v-model="form.followOrderNumber" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料编码">
              <el-input v-model="form.materialCode"disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据日期">
              <el-date-picker v-model="form.documentDate" type="date" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作员">
              <el-input v-model="form.operator" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="委外单号">
              <el-input v-model="form.outsourcingOrderNumber" disabled/>
              <el-link type="primary" style="margin-left: 8px;"@click="showOrderDialog=true">选择</el-link>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料名称">
              <el-input v-model="form.materialName" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据状态">
              <el-input v-model="form.documentStatus" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核人">
              <el-input v-model="form.auditor" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商">
              <el-input v-model="form.supplier" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计量单位">
              <el-input v-model="form.unitOfMeasurement" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="业务状态">
              <el-select v-model="form.businessStatus" placeholder="请选择" disabled>
                <el-option label="正常" value="正常" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核日期">
              <el-date-picker v-model="form.auditDate" type="date"  disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="退回仓库">
              <el-select v-model="form.returnWarehouse" placeholder="请选择">
                <el-option label="仓库A" value="A" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="委外数量">
              <el-input v-model="form.outsourcingQuantity" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注信息">
              <el-input v-model="form.remark" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 按钮区域 -->
        <div class="button-area" style="margin-top: 40px;">
          <el-button type="primary" @click="AddOutsourReturn()">保存</el-button>
          <el-button>取消</el-button>
          <el-button type="success">审核</el-button>
          <el-button type="warning">反审核</el-button>
          <el-button type="info">收起</el-button>
        </div>
      </el-form>
  
      <!-- 表格区域 -->
      <div class="table-area">
        <div style="margin-bottom: 10px;">
          <el-button type="primary" size="small" @click="dialogTableVisible=true">导入</el-button>
        </div>
        <el-table :data="tableData" border>
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="documentCode" label="发料单号" />
          <el-table-column prop="materialCode" label="物料编码" />
          <el-table-column prop="materialName" label="物料名称" />
          <el-table-column prop="unitOfMeasurement" label="主计量" />
          <el-table-column prop="returnQty" label="退料数量">
            <template #default="scope">
              <el-input v-model="scope.row.returnQty" @input="form.outsourcingreturnQutity = scope.row.returnQty" />
            </template>
          </el-table-column>
          <el-table-column prop="outsourcingQuantity" label="入库数量" />
          <el-table-column prop="remarkadx" label="备注" >
            <template #default="scope">
                <el-input type="textarea" v-model="scope.row.remarkadx" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-dialog v-model="showOrderDialog" title="选择委外订单" width="80%">
      <el-table :data="tableData1" border @selection-change="handleSelectionChange">
          <el-table-column prop="documentCode" label="单据编码" />
          <el-table-column prop="documentDate" label="单据日期">
            <template v-slot="scope">
                {{scope.row.documentDate.substring(0,10)}}
            </template>
          </el-table-column>
          <el-table-column prop="createdBy" label="创建人" />
          <el-table-column prop="documentStatus" label="单据状态" />
          <el-table-column prop="businessType" label="业务类型" />
          <el-table-column prop="businessStatus" label="业务状态" />
          <el-table-column prop="auditDate" label="审核日期" >
            <template v-slot="scope">
               <p v-if="scope.row.auditDate!='1900-01-01T00:00:00'">{{scope.row.auditDate.substring(0,10)}}</p>
               <p v-else> </p> 
            </template>
          </el-table-column>
          <el-table-column prop="auditor" label="审核人" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="primary" link style="margin-top: 10px;" @click="Handlrer(scope.row)">选择</el-button>
            </template>

          </el-table-column>
        
        </el-table>
        <el-button type="info" style="margin-top: 10px;" @click="showOrderDialog=false">关闭</el-button>
    </el-dialog>
      </div>

        <!-- 物料清单 -->
    <el-dialog v-model="dialogTableVisible" title="物料清单" width="1600">
     <!-- 表格 -->
     <el-table @selection-change="handleMaterialSelectionChange" border :data="tableData2" style="width: 100%" >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="materialsBliiId" type="index" label="序号" width="60"></el-table-column>
      <el-table-column prop="followOrderNumber" label="计划单号"></el-table-column>
      <el-table-column prop="documentDate" label="订单交期">
        <template #default="scope">
          {{ scope.row.documentDate.substring(0,10) }}
        </template>
      </el-table-column>
      <el-table-column prop="documentCode" label="单据编码"></el-table-column>
      <el-table-column prop="documentStatus" label="单据状态"></el-table-column>
      <el-table-column prop="businessType" label="业务类型"></el-table-column>
      <el-table-column prop="materialName" label="物料名称"></el-table-column>
      <el-table-column prop="materialCode" label="物料编码"></el-table-column>
      <el-table-column prop="unitOfMeasurement" label="主计量"></el-table-column>
      <el-table-column prop="outsourcingQuantity" label="生产数量"></el-table-column>
      <el-table-column prop="createdAt" label="单据日期">
        <template #default="scope">
          {{ scope.row.createdAt.substring(0,10) }}
        </template>
      </el-table-column>
    </el-table>
    <el-button type="primary" style="margin-top: 10px;" @click="confirmImport">确认</el-button>
    <el-button type="info" style="margin-top: 10px;" @click="dialogTableVisible=false">关闭</el-button>
  </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { onMounted, ref ,reactive} from 'vue'
  import {KongaUrl} from '@/axios/axiosHelp';
  import { ElMessage } from 'element-plus';
  import { useCounterStore } from '@/stores/counter';
  import { useRoute,useRouter } from 'vue-router';
  import axios from 'axios';  
  let router=useRouter();
  let store = useCounterStore();
  const form = reactive({
    documentCode: `WWTH${Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000}`,
    businessType: '',
    followOrderNumber: '',
    materialCode: '',
    remark: '',
    documentDate: '',
    operator: '',
    outsourcingOrderNumber: '',
    materialName: '',
    documentStatus: '',
    auditor: '',
    supplier: '',
    unitOfMeasurement: '',
    businessStatus: '',
    auditDate: new Date(),
    returnWarehouse: '',
    outsourcingQuantity: '',
    createdAt: new Date(),
    createdBy: store.user.userName,
    lastModifiedAt: new Date(),
    lastModifiedBy: store.user.userName,
    isDelete: 0,
    outsourcingreturnQutity: 0,
    pid:0,
    wuliaoCode:'',
    wuliaoName:'',
    zhujiliang:'',
    rukuQutity:0,
    beizhu:''
  })
  onMounted(()=>{
    getOutSourcingOrderList();
  })
  const qwea=reactive({
    outsourcingQuantity:'',
  })
  const tableData = ref([])
  const tableData1 = ref([])
  const showOrderDialog = ref(false)
  const page=reactive({
    pageindex:1,
    pagesize:15,
    DocumentCode:'',
    DocumentStatus:'',
    BusinessStatus:'',
    BeginData:'',
    EndData:'',
    totalpage:0,
    totalcount:0,
  })
  const selectedIds = ref([])
  const selectedMaterialse = ref([])
// 选择项变化
const handleSelectionChange = (val) => {
  selectedIds.value = val.map(item => item.id)
  console.log('选中的数据', selectedIds.value)
}
const handleMaterialSelectionChange = (val) => {
  selectedMaterials.value = val
  console.log('选中的物料数据', selectedMaterials.value)
}
  //查询单据方法
const getOutSourcingOrderList=()=>{
  KongaUrl({
        url:'/weiwaidu/api/OutSourc/QueryOutSourOrder',
        method:'get',
        params:{
            pageindex:page.pageindex,
            pagesize:page.pagesize,
            DocumentCode:page.DocumentCode,
            DocumentStatus:page.DocumentStatus,
            BusinessStatus:page.BusinessStatus,
            BeginData:page.BeginData,
            EndData:page.EndData,
        }
    })
    .then(res=>{
        if(res.data.code==101){
          tableData1.value=res.data.list;
            console.log('委外订单列表信息',tableData1.value)
            page.totalcount=res.data.totalcount
            page.totalpage=res.data.totalpage
        }
    })
}

const dialogTableVisible = ref(false)
const tableData2=ref([])
const selectedMaterials = ref([])
const form1 = reactive({
    Pid:'',
    pageindex:1,
    pagesize:15
});

const AddOutsourReturn=()=>{
  console.log('向后端传递的数据',form)                                                                                                                                                                                                                                                                                                                                                                           
  console.log('退料数量',qwea.outsourcingQuantity)
  KongaUrl({
    url:'/weiwaixie/api/Outsour/AddOutSourcingReturn',
    method:'post',
    data:form
  })
  .then(res=>{
    if(res.data.code==101){
      ElMessage.success('保存成功');
      router.push('/OutSourcingReturnShow')
    }
  })
}

// 搜索参数
const searchParams = reactive({
  salesOrderNo: "",
  billCode: "",
  materialCode: "",
  materialName: "",
  startDate: "", // 格式示例：'2023-10-01'
  endDate: "",
});
onMounted(()=>{
    searchProducts()
})
//显示
const searchProducts = () => {
  KongaUrl
    .get("/weiwaidu/api/OutSourc/QueryOutSourReleasePid", {
      params: {
       Pid:form1.Pid,
       pageindex:form1.pageindex,
       pagesize:form1.pagesize
      },
    })
    .then((res) => {
      tableData2.value = res.data.list;
      console.log('物料清单列表信息',tableData2.value)
      // 注意：后端返回的总记录数是 Data.PageCount，但需要根据总记录数计算总页数
      form1.TotalCount = res.data.data.pageCount; // 总记录数
      form1.PageCount = Math.ceil(form1.TotalCount / form1.PageSize); // 前端计算总页数
    })
    .catch((error) => {
      console.error("获取产品列表失败", error);
    });
};
// 新增：确认导入物料
const confirmImport = () => {
  tableData.value = [
    
    ...tableData.value,
    ...selectedMaterials.value.map((item, idx) => ({
       
      documentCode: item.documentCode,
      materialCode: item.materialCode,
      materialName: item.materialName,
      spec:  item.spec || '',
      unit: item.mainUnit,
      unitOfMeasurement: item.unitOfMeasurement,
      batchNo: item.planOrderNo,
      outsourcingQuantity:item.outsourcingQuantity,
      remark: item.remarks
    }))
    
  ]
  dialogTableVisible.value = false
  selectedMaterials.value = []
}
const Handlrer=(row)=>{
  console.log(row)
  form.businessType=row.businessType;
  form.materialCode=row.materialCode;
  form.documentDate=row.documentDate;
  form.operator=store.user.userName;
  form.followOrderNumber=row.documentCode;
  form.materialName=row.materialName;
  form.documentStatus=row.documentStatus;
  form.auditor='';
  form.outsourcingOrderNumber=row.documentCode;
  form.unitOfMeasurement='个';
  form.businessStatus=row.businessStatus;
  form.auditDate= new Date();
  form.supplier=row.supplier;
  form.outsourcingQuantity=row.outsourcingQuantity;
  form.remark='';
  form.pid=row.id;
  form.wuliaoCode=row.materialCode;
  form.wuliaoName=row.materialName;
  form.zhujiliang='个';
  form.rukuQutity=row.outsourcingQuantity;
  form.beizhu='';
  form1.Pid = row.id;
  searchProducts();
  showOrderDialog.value=false
}
//
  </script>
  
  <style scoped>
  .form-area {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
  }
  .button-area {
    position: absolute;
    top: 20px;
    right: 40px;
  }
  .table-area {
    margin-top: 20px;
    background: #fff;
    padding: 20px;
    border-radius: 4px;
  }
  </style>